#pragma once

#include <pthread.h>
#include <vector>
#include <queue>
#include "Thread.hpp"
#include "Mutex.hpp"
#include "Cond.hpp"
#include "Log.hpp"

namespace threadpool
{
    using namespace ThreadModule;
    using namespace MutexModule;
    using namespace CondModule;
    using namespace LogModule;

    static const int gnum = 5;
    template <typename T>
    class ThreadPool
    {
    private:
        // 构造函数私有
        ThreadPool(int num = gnum) : _num(num), _isrunning(false), _csleep_num(0)
        {
            for (int i = 0; i < _num; i++)
            {
                _threads.emplace_back(
                    [this]()
                    {
                        HandlerTask();
                    });
            }
        }

        // 拷贝构造和赋值重载禁用
        ThreadPool(const ThreadPool<T> &threadpool) = delete;
        ThreadPool &operator =(const ThreadPool<T> &threadpool) = delete;

        void WakeUpAllThread()
        {
            LOG(LogLevel::DEBUG) << "唤醒全部线程";
            {
                MutexGuard mutexguard(_mutex);
                // 有线程休眠才唤醒
                if (_csleep_num > 0)
                    _cond.Broadcast();
            }
        }
    public:
        void Start()
        {
            if (_isrunning)
                return;
            _isrunning = true;
            for (auto &thread : _threads)
            {
                thread.Start();
                LOG(LogLevel::DEBUG) << "线程启动了, " << thread.GetName();
            }
        }

        void Stop()
        {
            if (!_isrunning)
                return;
            _isrunning = false;
            // 唤醒所有线程
            WakeUpAllThread();
        }

        void HandlerTask()
        {
            while (true)
            {
                T t;
                {
                    MutexGuard mutexguard(_mutex);
                    while (_isrunning && _q.empty())
                    {
                        _csleep_num++;
                        _cond.Wait(_mutex);
                        _csleep_num--;
                    }
                    // running为false && 队列为空
                    if (!_isrunning && _q.empty())
                    {
                        break;
                    }
                    t = _q.front();
                    _q.pop();
                }
                t();
            }
        }

        // 生产者发任务
        void EnQueue(const T &data)
        {
            if (!_isrunning)
                return;
            // 加锁：生产者消费者互斥，生产者和生产者互斥
            // 条件变量：生产者消费者同步
            {
                MutexGuard mutexguard(_mutex);
                _q.push(data);
                // 全部都在休眠，唤醒一个
                if (_csleep_num == _num)
                    _cond.Signal();
            }
        }

        void Join()
        {
            if (_isrunning)
                return;
            for (auto &thread : _threads)
            {
                thread.Join();
                LOG(LogLevel::DEBUG) << "线程 " << thread.GetName() << " 回收成功";
            }
        }

        static ThreadPool<T> *GetInstance()
        {
            LOG(LogLevel::DEBUG) << "获取单例";
            if (_inst == nullptr)
            {
                MutexGuard mutexguard(_mutex_inst);
                if (_inst == nullptr)
                {
                    LOG(LogLevel::DEBUG) << "首次使用单例，创建";
                    _inst = new ThreadPool<T>();
                    _inst->Start();
                }
            }
            return _inst;
        }

    private:
        std::vector<Thread> _threads; // 线程数组
        int _num;                     // 线程的数量
        std::queue<T> _q;             // 任务队列

        Mutex _mutex;    // 锁
        Cond _cond;      // 为空的条件变量
        int _csleep_num; // 消费者休眠数量

        bool _isrunning; // 运行状态

        static ThreadPool<T> *_inst; // 单例指针
        static Mutex _mutex_inst;    // 单例锁
    };

    // 静态成员属性类外初始化
    template <typename T>
    ThreadPool<T> *ThreadPool<T>::_inst = nullptr;
    template <typename T>
    Mutex ThreadPool<T>::_mutex_inst;
}